package com.linkage.order.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

















import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import com.linkage.book.pojo.Book;
import com.linkage.order.pojo.Order;
import com.linkage.order.pojo.OrderLine;
import com.linkage.order.repository.OrderRepository;
import com.linkage.user.pojo.User;
import com.linkage.user.service.UserService;
/**
 * 
 * @author XiaMingYu
 *
 */
@Service
public class OrderService {
	@Autowired
	private OrderRepository orderRepository;
	public List<Order> queryAll(){

		return this.orderRepository.queryAll();		
	}
		
    public OrderLine loadOneOrderLine(String orderId){
    	return this.orderRepository.loadOneOrderLine(orderId);
    }
    
    public Order generateOrder(HttpServletRequest request){
    	User user=(User)request.getSession().getAttribute("LOGIN_USER_KEY_IN_SESSION");
    	Order order = new Order();
    	order.setOrderId(UUID.randomUUID().toString().replace("-", "").toUpperCase());
    	order.setUserId(user.getUserId());
    	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	order.setOrderTime(df.format(new Date()));
    	order.setTotal(1);
    	order.setStatus(1);
    	order.setQuantity(1);
    	order.setAddress("nanjing");
    	this.saveOrder(order);
    	return order;
    }
     
    public OrderLine generateOrderLine(HttpServletRequest request,Book book){
    	Order order = this.generateOrder(request);
    	OrderLine orderLine = new OrderLine();
    	orderLine.setAddress(order.getAddress());
    	orderLine.setBookId(book.getBookId());
    	orderLine.setBookIdQuantity(1);
    	orderLine.setOrderId(order.getOrderId());
    	orderLine.setOrderTime(order.getOrderTime());
    	orderLine.setPrice(order.getTotal());
    	orderLine.setSubTotal(order.getTotal());
    	orderLine.setStatus(1); 
    	return orderLine;
    }
    
	public void saveOrder(Order order){
		this.orderRepository.saveOrder(order);
	}
	
	public void saveOrderLine(OrderLine orderLine){
		this.orderRepository.saveOrderLine(orderLine);
	}
	
	public void deleteOrder(String orderId){
		this.orderRepository.deleteOrder(orderId);
	}
	
	public Order findOrderById(String orderId){
		return this.orderRepository.findOrderById(orderId);
	}
	
	public void payOrder(@PathVariable("orderId")String orderId){
	    this.orderRepository.payOrder(orderId);
	}
	
	/*public void deliver(String orderId){
	    order = this.orderRepository.findOrderById(orderId);
		if(order.getStatus()!=2){
			return;
		}
		else 
		order.setStatus(3);
		return;
	}
	*/
	public void confirm(Order order){
		this.orderRepository.confirm(order);
		//order.setStatus(4);
		}
	
	public Order loadOneOrder(String orderId){
		return this.orderRepository.loadOneOrder(orderId);
	}
}



